package com.tg.app.adapter;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.EventConstants;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.joooonho.SelectableRoundedImageView;
import com.tg.app.R;
import com.tg.app.helper.DeviceHelper;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.data.bean.DeviceItem;
import com.tg.data.http.entity.EventMessageBean;

import java.util.List;

/**
 * Describe:
 * Created by Rance Rang on 2019/2/20.
 * <p>
 * Copyright (c) Tange.Inc All rights reserved.
 */
    public class PlaybackEventAdapter extends RecyclerView.Adapter<PlaybackEventAdapter.EventSimpleViewHolder> {

    private static final String TAG = "PlaybackEventAdapter";
    private List<EventMessageBean> eventList;
    private int selectedIndex = -1;        //记录当前选中的条目索引
    private Context context;
    private DeviceItem mDeviceItem;
    private int viewTypeAiEmpty = 0x01;
    public void setType(int mType) {
        this.mType = mType;
    }

    private int mType;

    public interface OnItemListener {
        void onClick(int position);
    }

    private OnItemListener mOnItemListener;

    public PlaybackEventAdapter(Context context, List<EventMessageBean> eventList) {
        this.eventList = eventList;
        this.context = context;
    }

    public void setDeviceItem(DeviceItem deviceItem) {
        mDeviceItem = deviceItem;
    }

    public void setSelectedIndex(int position) {
        this.selectedIndex = position;
    }

    public int getSelectedIndex() {
        return selectedIndex;
    }

    public void setListener(OnItemListener onItemListener) {
        mOnItemListener = onItemListener;
    }

    @NonNull
    @Override
    public PlaybackEventAdapter.EventSimpleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if (viewType == R.layout.playback_event_view_ai_empty){
            view = LayoutInflater.from(context).inflate(R.layout.playback_event_view_ai_empty, parent, false);
            return new EventSimpleViewHolder(view);
        }
        if (DeviceHelper.isCar(mDeviceItem) && mType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
            view = LayoutInflater.from(context).inflate(R.layout.playback_event_view_4g, parent, false);
        } else {
            view = LayoutInflater.from(context).inflate(R.layout.playback_event_view, parent, false);
        }
        return new PlaybackEventViewHolder(view);
    }

    @Override
    public int getItemViewType(int position) {
        EventMessageBean msg = eventList.get(position);
        if (TextUtils.equals(msg.getTag(),EventConstants.EMPTY)){
            return R.layout.playback_event_view_ai_empty;
        }
        return super.getItemViewType(position);
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onBindViewHolder(@NonNull PlaybackEventAdapter.EventSimpleViewHolder holder, final int position) {
        EventMessageBean msg = eventList.get(position);
        String imagePath = msg.getImage_path();
        ViewGroup.MarginLayoutParams imageParams = (ViewGroup.MarginLayoutParams) holder.ivImage.getLayoutParams();
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) holder.relLayout.getLayoutParams();
        boolean isEventView = holder instanceof PlaybackEventViewHolder;
        if (isEventView){
            PlaybackEventViewHolder viewHolder = (PlaybackEventViewHolder) holder;
            if (StringUtils.isEmpty(imagePath)) {
                viewHolder.ivImage.setVisibility(View.GONE);
            } else {
                try {
                    Glide.with(context).load(msg.getImage_path()).apply(new RequestOptions().error(R.mipmap.virtual).placeholder(R.mipmap.virtual)).into(viewHolder.ivImage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                viewHolder.ivImage.setVisibility(View.VISIBLE);
            }

            if (DeviceHelper.isCar(mDeviceItem)&&mType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
                eventList.get(position).setTag(EventConstants.GSENSOR);
            }

            viewHolder.tvTime.setVisibility(View.VISIBLE);
            int time = msg.getEndTimeSec() - msg.getStartTimeSec();

            String text = context.getResources().getString(R.string.message_event_unknown);

            EventMessageBean bean = eventList.get(position);

            if (bean == null) {
                return;
            }

            if (!TextUtils.isEmpty(bean.getTag())) {
                if (!TextUtils.isEmpty(bean.getTag_msg())) {
                    text = bean.getTag_msg();
                } else if (!TextUtils.isEmpty(bean.getTag_name())) {
                    text = bean.getTag_name();
                } else {
                    text = context.getResources().getString(R.string.message_event_unknown);
                }


                if (!StringUtils.isEmpty(text)) {
                    if (DeviceHelper.isCar(mDeviceItem) && mType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
                        String name = text + " " + videoLen(time);
                        viewHolder.tvName.setText(name);
                    } else {
                        viewHolder.tvName.setText(text);
                    }
                } else {
                    viewHolder.tvName.setText(videoLen(time));
                }

                if (!TextUtils.isEmpty(bean.getTag_icon())) {
                    Glide.with(context).load(bean.getTag_icon()).apply(new RequestOptions().placeholder(com.tg.message.R.drawable.ic_tange_global_icon_unknown).error(com.tg.message.R.drawable.ic_tange_global_icon_unknown)).into(viewHolder.ivIcon);
                } else {
                    viewHolder.ivIcon.setImageResource(com.tg.message.R.drawable.ic_tange_global_icon_unknown);
                }

            } else {
                viewHolder.ivIcon.setImageResource(com.tg.message.R.drawable.ic_tange_global_icon_unknown);
            }

            if (!StringUtils.isEmpty(text)) {
                if (DeviceHelper.isCar(mDeviceItem) && mType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
                    String name = text + " " + videoLen(time);
                    viewHolder.tvName.setText(name);
                } else {
                    viewHolder.tvName.setText(text);
                }
            } else {
                viewHolder.tvName.setText(videoLen(time));
            }

            viewHolder.tvTime.setText(videoLen(time));
            viewHolder.tvStartTime.setText(DateUtil.formatTimeHHmmss(msg.getStartTimeSec()));
            if (DeviceHelper.isCar(mDeviceItem) && mType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
                layoutParams.leftMargin = DimenUtil.dp2px(context, 10);
                imageParams.rightMargin = DimenUtil.dp2px(context, 10);
                imageParams.width = DimenUtil.dp2px(context, 80);
                viewHolder.ivImage.setVisibility(View.INVISIBLE);
                viewHolder.tvTime.setVisibility(View.INVISIBLE);
            }
        }else{
            String startStr =  msg.getStart_time().substring(11,16);
            String endStr = msg.getEnd_time().substring(11,16);
            if (position==0&&msg.getId()==1000){
                endStr = context.getResources().getString(R.string.message_event_ai_empty_today_last);
            }
            holder.tvName.setText(String.format(context.getResources().getString(R.string.message_event_ai_empty),startStr,endStr));
        }
        if (this.selectedIndex == position) {
            layoutParams.leftMargin = DimenUtil.dp2px(context, 0);
            imageParams.rightMargin = DimenUtil.dp2px(context, isEventView?10:0);
            holder.relLayout.setAlpha(1f);

        } else {
            layoutParams.leftMargin = DimenUtil.dp2px(context, 20);
            imageParams.rightMargin = DimenUtil.dp2px(context, 0);
            holder.relLayout.setAlpha(0.3f);
        }
        holder.relLayout.setLayoutParams(layoutParams);
        holder.ivImage.setLayoutParams(imageParams);
        holder.itemView.setOnClickListener(view -> {
            if (mOnItemListener != null) {
                mOnItemListener.onClick(position);
            }
        });
    }
    private String videoLen(int time) {
        StringBuffer buffer = new StringBuffer();
        int minutes = time / 60;
        int seconds = time % 3600 % 60;
        if (minutes > 0) {
            buffer.append(minutes + "'");
        }
        if (seconds > 0) {
            buffer.append(seconds + "''");
        }
        return buffer.toString();
    }

    @Override
    public void onViewRecycled(@NonNull EventSimpleViewHolder holder) {
        super.onViewRecycled(holder);
        if(holder instanceof PlaybackEventViewHolder){
            PlaybackEventViewHolder viewHolder  = (PlaybackEventViewHolder) holder;
            SelectableRoundedImageView imageView = viewHolder.ivImage;
            if (imageView != null) {
                Glide.with(context).clear(imageView);
            }
        }

    }

    @Override
    public int getItemCount() {
        return eventList == null ? 0 : eventList.size();
    }

    class EventSimpleViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;
        RelativeLayout relLayout;
        SelectableRoundedImageView ivImage;
        public EventSimpleViewHolder(@NonNull View itemView) {
            super(itemView);
            ivImage = itemView.findViewById(R.id.iv_playback_event_view);
            relLayout = itemView.findViewById(R.id.rel_playback_event_view);
            tvName = itemView.findViewById(R.id.tv_playback_event_view_name);
        }
    }
    class PlaybackEventViewHolder extends EventSimpleViewHolder {
        TextView tvTime, tvStartTime;
        ImageView ivIcon;
        RelativeLayout relLayout;

        PlaybackEventViewHolder(View itemView) {
            super(itemView);
            tvStartTime = itemView.findViewById(R.id.tv_playback_event_view_time);
            tvTime = itemView.findViewById(R.id.tv_playback_event_view_time_total);
            ivIcon = itemView.findViewById(R.id.playback_event_view_icon);

        }
    }


}
